import React, { useRef, useEffect } from 'react';
import MessageItem from './MessageItem';
import './MessageList.css';

const MessageList = ({ messages, onTypingComplete }) => {
    const messagesEndRef = useRef(null);
    const containerRef = useRef(null);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ 
            behavior: "smooth",
            block: "end"
        });
    };

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    // 当消息内容更新时也滚动到底部（用于流式输出）
    useEffect(() => {
        const lastMessage = messages[messages.length - 1];
        if (lastMessage && lastMessage.isStreaming) {
            scrollToBottom();
        }
    }, [messages]);

    return (
        <div className="message-list" ref={containerRef}>
            <div className="messages-container">
                {messages.map((message, index) => (
                    <MessageItem
                        key={message.id}
                        message={message}
                        isLast={index === messages.length - 1}
                        onTypingComplete={onTypingComplete}
                    />
                ))}
                <div ref={messagesEndRef} />
            </div>
        </div>
    );
};

export default MessageList;
